package com.glorious.gcontacts.contacts.spring.services;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glorious.gcontacts.login.data.GoogleContactsAppData;
import com.glorious.gcontacts.login.exceptions.NotLoggedOnGoogleContactsException;
import com.glorious.gcontacts.model.UserData;
import com.glorious.gcontacts.spring.services.UsersService;
import com.google.appengine.api.users.User;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactGroupEntry;
import com.google.gdata.data.contacts.ContactGroupFeed;

@Service
public class GoogleContactsService
{
	private UsersService usersService;
	
	@Autowired
	public void setUsersService(UsersService usersService)
	{
		this.usersService = usersService;
	}

	private ContactsService getContactsService(User user) throws Exception
	{
		ContactsService service = new ContactsService("test");
		UserData data = usersService.getUserData(user);
		if(data.getGoogleContactInfo() != null && data.getGoogleContactInfo().getAuthToken() != null && data.getGoogleContactInfo().getAuthTokenSecret() != null)
		{
			GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
			oauthParameters.setOAuthConsumerKey(GoogleContactsAppData.CONSUMER_KEY);
			oauthParameters.setOAuthConsumerSecret(GoogleContactsAppData.CONSUMER_SECRET);
			oauthParameters.setOAuthToken(data.getGoogleContactInfo().getAuthToken());
			oauthParameters.setOAuthTokenSecret(data.getGoogleContactInfo().getAuthTokenSecret());
			service.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
		}
		else
		{
			throw new NotLoggedOnGoogleContactsException();
		}
		return service;
	}
	
	public List<String> getGroups(User user) throws Exception
	{
		List<String> lista = new ArrayList<String>();
		ContactsService service = getContactsService(user);
		ContactGroupFeed feed = service.getFeed(new URL("https://www.google.com/m8/feeds/groups/default/full"), ContactGroupFeed.class);
		for(ContactGroupEntry entry: feed.getEntries())
		{
			lista.add(entry.getTitle().getPlainText());
		}
		return lista;
	}
}
